<template>
  <div class="blog" ref="blogDom" @scroll="scrollSendRequest">
    <transition appear appear-active-class="fadeInUpMini">
      <search-bar :getList="getList"></search-bar
    ></transition>
    <blog-item v-for="item in blogList" :key="item.id" :blog="item"></blog-item>
  </div>
</template>

<script setup lang="ts">
import BlogItem from "./blogItem.vue";
import SearchBar from "@/componentMobile/SearchBar.vue";
import { Tblog } from "@/type/blog";
import axios from "@/http";
import { ref, onMounted, computed, nextTick } from "vue";
const blogList = ref<Tblog[]>([]);
const pageSize = ref<number>(7);
const pageNum = ref<number>(1);
const blogDom = ref<HTMLDivElement | null>(null);
const total = ref<number>(1);
let lastTitle: string | null | undefined = null;
onMounted(() => {
  getBlogList();
});
const getBlogList = (title?: string, reset?: boolean) => {
  if (!reset && title === lastTitle) return;
  if (!reset) pageNum.value = 1;
  return new Promise((resolve) => {
    axios
      .get("/blog/pagelist", {
        params: {
          pageNum: pageNum.value,
          pageSize: pageSize.value,
          title,
        },
      })
      .then((res) => {
        lastTitle = title;
        blogList.value = [...blogList.value, ...res.data.data.recordList];
        total.value = res.data.data.total;
      })
      .finally(() => {
        resolve(true);
      });
  });
};
const getList = (title?: string) => {
  if (title === lastTitle) return;
  pageNum.value = 1;
  axios
    .get("/blog/pagelist", {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        title,
      },
    })
    .then((res) => {
      lastTitle = title;
      blogList.value = res.data.data.recordList;
      total.value = res.data.data.total;
    });
};
const limitTime = ref<boolean>(false);
const domHeight = computed(() => blogDom.value?.getBoundingClientRect().height);
const scrollSendRequest = (e: any) => {
  if (limitTime.value) return;
  if (total.value <= blogList.value.length) return;
  if (domHeight.value + e.target.scrollTop + 100 > e.target.scrollHeight) {
    limitTime.value = true;
    pageNum.value++;
    getBlogList(lastTitle!, true)?.then(() => {
      limitTime.value = false;
    });
  }
};
</script>

<style scoped lang="scss">
.blog {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  overflow: auto;
  padding-top: 40px;
}
</style>
